from django.views import View
import random
import logging
from django_redis import get_redis_connection
from django import http

from verifications.libs.captcha import captcha
# from nxh_mall.celery_tasks.sms.SendSMS import CPP
# 设置mark as source root为导包路径
# from verifications.libs.captcha import captcha
from . import constants
from celery_tasks.sms.tasks import send_sms_code
from nxh_mall.utils import response_code

# 创建输出器
logger = logging.getLogger('django')


# Create your views here.


class ImageCodeView(View):
    def get(self, request, uuid):
        """

        :param request:
        :param uuid:
        :return: image
        """
        # 接受参数
        # 校验
        # 实现逻辑生成，保存，响应
        text, image = captcha.captcha.generate_captcha()
        redis_conn = get_redis_connection(alias='verify_code')
        redis_conn.setex(name='image_%s' % uuid, time=constants.IMAGE_CODE_REDIS_EXPIRES, value=text)
        return http.HttpResponse(image, content_type='image/jpg')


class SMSCodeView(View):
    def get(self, request, mobile):
        """
        接受图形验证相关参数：手机号，图形验证码，uuid
        redis读取短息验证码
        对比验证码
        生成短信验证码
        保存短信验证码=redis-【手机号：验证码】
        发送短信验证码----》判断响应数据时间是否超时
        响应结果
        """
        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        if not all([mobile, image_code_client, uuid]):
            return http.HttpResponseForbidden('缺少必要参数')

        redis_conn = get_redis_connection(alias='verify_code')
        image_code_server = redis_conn.get('image_%s' % uuid)
        if image_code_server is None:
            data = {'code': response_code.RETCODE.IMAGECODEERR,
                    'errmsg': '图形验证码已失效'}
            return http.JsonResponse(data)
        # 校验短信验证码
        sms_send_flag = redis_conn.get('sms_send_flag_%s' % mobile)
        if not sms_send_flag is None:
            data = {'code': response_code.RETCODE.THROTTLINGERR,
                    'errmsg': '图形验证码发送过于频繁'}
            return http.JsonResponse(data)
        # 删除rendis中图形验证码
        redis_conn.delete('image_%s' % uuid)
        # 对比验证码是否正确 统一转小写进行对比
        image_code_server = image_code_server.decode()  # 转字符串编码
        if image_code_client.lower() != image_code_server.lower():
            data = {'code': response_code.RETCODE.IMAGECODEERR,
                    'errmsg': '图形验证码输出有误'}
            return http.JsonResponse(data)
        # 生产随机验证码,不满足6位前面补0
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)  # 手动输出日志，记录短信验证码
        # # 保存验证码
        # redis_conn.setex('sms_code_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # # 后端校验短信验证码的有效时间
        # redis_conn.setex('sms_send_flag_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, 1)

        pl = redis_conn.pipeline()  # 创建管道,批量保存
        pl.setex('sms_code_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('sms_send_flag_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, 1)
        pl.execute()
        # celery发送短信验证码
        # 发送短信验证码 5分钟有效期
        # CPP().send_message(mobile=mobile, datas=[sms_code, 5], tid=constants.SEND_SMS_TEMPLATE_ID)
        #异步发送短信
        send_sms_code.delay(mobile=mobile, sms_code=sms_code, tid=constants.SEND_SMS_TEMPLATE_ID)

        data = {'code': response_code.RETCODE.OK,
                'errmsg': '短信验证码发送成功'}
        return http.JsonResponse(data)
